# +----------------------------------------------------------------------
# | DjangoAdmin敏捷开发框架 [ 赋能开发者，助力企业发展 ]
# +----------------------------------------------------------------------
# | 版权所有 2021~2024 北京DjangoAdmin研发中心
# +----------------------------------------------------------------------
# | Licensed LGPL-3.0 DjangoAdmin并不是自由软件，未经许可禁止去掉相关版权
# +----------------------------------------------------------------------
# | 官方网站: https://www.djangoadmin.cn
# +----------------------------------------------------------------------
# | 作者: @一米阳光 团队荣誉出品
# +----------------------------------------------------------------------
# | 版权和免责声明:
# | 本团队对该软件框架产品拥有知识产权（包括但不限于商标权、专利权、著作权、商业秘密等）
# | 均受到相关法律法规的保护，任何个人、组织和单位不得在未经本团队书面授权的情况下对所授权
# | 软件框架产品本身申请相关的知识产权，禁止用于任何违法、侵害他人合法权益等恶意的行为，禁
# | 止用于任何违反我国法律法规的一切项目研发，任何个人、组织和单位用于项目研发而产生的任何
# | 意外、疏忽、合约毁坏、诽谤、版权或知识产权侵犯及其造成的损失 (包括但不限于直接、间接、
# | 附带或衍生的损失等)，本团队不承担任何法律责任，本软件框架禁止任何单位和个人、组织用于
# | 任何违法、侵害他人合法利益等恶意的行为，如有发现违规、违法的犯罪行为，本团队将无条件配
# | 合公安机关调查取证同时保留一切以法律手段起诉的权利，本软件框架只能用于公司和个人内部的
# | 法律所允许的合法合规的软件产品研发，详细声明内容请阅读《框架免责声明》附件；
# +----------------------------------------------------------------------

from datetime import datetime, timedelta, date

from fastapi.logger import logger
from sqlalchemy import and_, text, orm
from werkzeug.datastructures.structures import MultiDict

from apps.constants.message import PAGE_LIMIT
from apps.models.data import Data
from apps.models.user import User
from apps.forms.company import CompanyForm
from extends import db
from utils import R, regular
from utils.utils import uid


async def saleRoomData(request):
    userID = uid(request)
    user = None
    if userID != 1:
        user = db.query(User).filter(User.id == userID).first()
    dateType = int(request.query_params.get("dateType", 3))
    list = []
    if dateType == 1:  # 最近七天统计
        # 获取今天的日期
        today = datetime.now().date()
        # 循环输出最近七天的日期
        for i in range(6, -1, -1):
            day = today - timedelta(days=i)
            sql = text(
                "select sum(sale_money) as money from fastapi_data where day = :day")
            params = {'day': day}
            if user:
                sql = text(
                    "select sum(sale_money) as money from fastapi_data where company_id = :company_id and day = :day")
                params['company_id'] = user.company_id
            result = db.execute(sql, params).first()
            money = 0.00
            if result[0]:
                money = result[0]
            data = {'key': '{0}'.format(day), 'value': '{0}'.format(money)}
            list.append(data)
    elif dateType == 2:  # 本月统计
        today = datetime.today()
        # 循环输出今天之前本月的所有日期
        for day in range(1, today.day + 1):
            date_to_print = today.replace(day=day)
            nDay = date_to_print.strftime("%Y-%m-%d")
            sql = text(
                "select sum(sale_money) as money from fastapi_data where day = :day")
            params = {'day': nDay}
            if user:
                sql = text(
                    "select sum(sale_money) as money from fastapi_data where company_id = :company_id and day = :day")
                params['company_id'] = user.company_id
            result = db.execute(sql, params).first()
            money = 0.00
            if result[0]:
                money = result[0]
            data = {'key': '{0}'.format(nDay), 'value': '{0}'.format(money)}
            list.append(data)
    else:  # 本年
        year = datetime.now().year
        now = datetime.now().month
        for i in range(1, now + 1):
            sql = text(
                "SELECT sum(sale_money) from (select max(id) as id from fastapi_data where year = :year and month = :month group by shop_num) as latest_records JOIN fastapi_data r ON r.id = latest_records.id")
            params = {'year': "{0}".format(year), 'month': i}
            if user:
                sql = text(
                    "SELECT sum(sale_money) from (select max(id) as id from fastapi_data where company_id = :company_id and year = :year and month = :month group by shop_num) as latest_records JOIN fastapi_data r ON r.id = latest_records.id")
                params['company_id'] = user.company_id
            result = db.execute(sql, params).first()
            money = 0.00
            if result[0]:
                money = result[0]
            data = {'key': '{0}月'.format(i), 'value': '{0}'.format(money)}
            list.append(data)

    return R.ok(data=list)


async def saleTotal(request):
    userID = uid(request)
    user = None
    if userID != 1:
        user = db.query(User).filter(User.id == userID).first()
    sql = text(
        "SELECT sum(sale_money),sum(sale_num),sum(completed_order) from (select max(id) as id from fastapi_data group by shop_num) as latest_records JOIN fastapi_data r ON r.id = latest_records.id")
    params = {}
    if user:
        params['company_id'] = user.company_id
        sql = text(
            "SELECT sum(sale_money),sum(sale_num),sum(completed_order) from (select max(id) as id from fastapi_data where company_id = :company_id group by shop_num) as latest_records JOIN fastapi_data r ON r.id = latest_records.id")
    result = db.execute(sql, params).first()
    # 店铺总数
    shopNumsql = text("select count(distinct shop_num) from fastapi_data")
    params = {}
    if user:
        params['company_id'] = user.company_id
        shopNumsql = text(
            "select count(distinct shop_num) from fastapi_data where company_id = :company_id")
    shopResult = db.execute(shopNumsql, params).first()
    # 退款和推广金额
    today = date.today()
    yesterday = today - timedelta(days=1)
    params = {'day': yesterday}
    refundSql = text("select sum(tg_amount),sum(refund_money) from fastapi_data where day = :day")
    if user:
        params['company_id'] = user.company_id
        refundSql = text(
            "select sum(tg_amount),sum(refund_money) from fastapi_data where day = :day and company_id = :company_id")
    refundResult = db.execute(refundSql, params).first()

    refund_money = tg_money = completed_order = sale_num = sale_money = 0.00
    shop_num = 0
    if result[0]:
        sale_money = result[0]
    if result[1]:
        sale_num = result[1]
    if result[2]:
        completed_order = result[2]
    if shopResult[0]:
        shop_num = shopResult[0]
    if refundResult[0]:
        tg_money = refundResult[0]
    if refundResult[1]:
        refund_money = refundResult[1]
    data = {
        'sale_money': "{0}".format(sale_money),
        'sale_num': "{0}".format(sale_num),
        'completed_order': "{0}".format(completed_order),
        'shop_num': "{0}".format(shop_num),
        'tg_money': "{0}".format(tg_money),
        'refund_money': "{0}".format(refund_money)
    }
    return R.ok(data=data)
